package org.xxpay.manage.config.ctrl;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.xxpay.core.common.constant.Constant;
import org.xxpay.core.common.constant.MchConstant;
import org.xxpay.core.common.constant.PayConstant;
import org.xxpay.core.common.constant.RetEnum;
import org.xxpay.core.common.domain.BizResponse;
import org.xxpay.core.common.domain.XxPayPageRes;
import org.xxpay.core.common.domain.XxPayResponse;
import org.xxpay.core.common.util.DateUtil;
import org.xxpay.core.entity.*;
import org.xxpay.manage.common.ctrl.BaseController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: dingzhiwei
 * @date: 18/1/17
 * @description:
 */
@RestController
@RequestMapping(Constant.MGR_CONTROLLER_ROOT_PATH)
public class DataController extends BaseController {

    /**
     * 统计用户数据
     * @return
     */
    @RequestMapping("/statistics/count4user")
    @ResponseBody
    public ResponseEntity<?> count4User(HttpServletRequest request) {
        // 商户数据
        Map mchObj = commonService.mchInfoService.count4Mch();
        // 代理商数据
        Map agentObj = commonService.agentInfoService.count4Agent();

        JSONObject object = new JSONObject();
        object.put("mchObj", doMapEmpty(mchObj));
        object.put("agentObj", doMapEmpty(agentObj));
        return ResponseEntity.ok(XxPayResponse.buildSuccess(object));
    }

    /**
     * 统计收入数据
     * @return
     */
    @RequestMapping("/statistics/count4income")
    @ResponseBody
    public ResponseEntity<?> count4Income(HttpServletRequest request) {
        Map totalIncome = commonService.payOrderService.count4Income(null, null, MchConstant.PRODUCT_TYPE_PAY, null, null);
        if(null == totalIncome.get("totalAgentProfit")) totalIncome.put("totalAgentProfit", 0);
        if(null == totalIncome.get("totalParentAgentProfit")) totalIncome.put("totalParentAgentProfit", 0);
        totalIncome.put("totalAgentProfit", Long.valueOf(String.valueOf((totalIncome.get("totalAgentProfit")))) +  Long.valueOf(String.valueOf((totalIncome.get("totalParentAgentProfit")))));
        JSONObject object = new JSONObject();
        object.put("totalIncome", doMapEmpty(totalIncome));
        return ResponseEntity.ok(XxPayResponse.buildSuccess(object));
    }

    /**
     * 统计今昨日数据
     * @return
     */
    @RequestMapping("/statistics/count4dayIncome")
    @ResponseBody
    public ResponseEntity<?> count4DayIncome(HttpServletRequest request) {
        // 今日
        String today = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String todayStart = today + " 00:00:00";
        String todayEnd = today + " 23:59:59";
        // 昨日
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -1);
        String yesterday = new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
        String yesterdayStart = yesterday + " 00:00:00";
        String yesterdayEnd = yesterday + " 23:59:59";
        // 今日收款统计
        Map todayPayData = commonService.payOrderService.count4Income(null, null, MchConstant.PRODUCT_TYPE_PAY, todayStart, todayEnd);
        // 今日充值统计
        Map todayRechargeData = commonService.payOrderService.count4Income(null, null, MchConstant.PRODUCT_TYPE_RECHARGE, todayStart, todayEnd);
        // 今日代付统计`
        Map todayAgentpayData = commonService.mchAgentpayService.count4All(null, null, null, null, null, PayConstant.AGENTPAY_STATUS_SUCCESS, null, null, null, todayStart, todayEnd);
        // 昨日收款统计
        Map yesterdayPayData = commonService.payOrderService.count4Income(null, null, MchConstant.PRODUCT_TYPE_PAY, yesterdayStart, yesterdayEnd);
        // 昨日充值统计
        Map yesterdayRechargeData = commonService.payOrderService.count4Income(null, null, MchConstant.PRODUCT_TYPE_RECHARGE, yesterdayStart, yesterdayEnd);
        // 昨日代付统计
        Map yesterdayAgentpayData = commonService.mchAgentpayService.count4All(null, null, null, null, null, PayConstant.AGENTPAY_STATUS_SUCCESS, null, null, null, yesterdayStart, yesterdayEnd);
        // 全部收款统计
        Map totalPayData = commonService.payOrderService.count4Income(null, null, MchConstant.PRODUCT_TYPE_PAY, null, null);
        // 全部充值统计
        Map totalRechargeData = commonService.payOrderService.count4Income(null, null, MchConstant.PRODUCT_TYPE_RECHARGE, null, null);
        // 全部代付统计
        Map totalAgentpayData = commonService.mchAgentpayService.count4All(null, null, null, null, null, PayConstant.AGENTPAY_STATUS_SUCCESS, null, null, null, null, null);

        JSONObject object = new JSONObject();
        object.put("todayPayData", doMapEmpty(todayPayData));
        object.put("todayRechargeData", doMapEmpty(todayRechargeData));
        object.put("todayAgentpayData", doMapEmpty(todayAgentpayData));
        object.put("yesterdayPayData", doMapEmpty(yesterdayPayData));
        object.put("yesterdayRechargeData", doMapEmpty(yesterdayRechargeData));
        object.put("yesterdayAgentpayData", doMapEmpty(yesterdayAgentpayData));
        object.put("totalPayData", doMapEmpty(totalPayData));
        object.put("totalRechargeData", doMapEmpty(totalRechargeData));
        object.put("totalAgentpayData", doMapEmpty(totalAgentpayData));
        return ResponseEntity.ok(XxPayResponse.buildSuccess(object));
    }


    /**
     * 统计代理商数据
     * @return
     */
    @RequestMapping("/statistics/count4agent")
    @ResponseBody
    public ResponseEntity<?> count4Agent(HttpServletRequest request) {
        // 代理商数据
        Map agentObj = commonService.agentInfoService.count4Agent();
        // 代理商分润数据
        Map agentProfitObj = new JSONObject();
        Long rechargeProfit = 0l;
        Long totalProfit = 0l;
        Long payProfit = 0l;
        Long agentpayProfit = 0l;
        List<Map> mapList = commonService.agentAccountHistoryService.count4AgentProfit(null);
        for(Map map : mapList) {
            String bizItem = map.get("bizItem").toString();
            Long profilt = Long.parseLong(map.get("totalProfit").toString());
            switch (bizItem) {
                case MchConstant.BIZ_ITEM_PAY:
                    totalProfit += profilt;
                    payProfit += profilt;
                    break;
                case MchConstant.BIZ_ITEM_AGENTPAY:
                    totalProfit += profilt;
                    agentpayProfit += profilt;
                    break;
                case MchConstant.BIZ_ITEM_OFF:
                    totalProfit += profilt;
                    rechargeProfit += profilt;
                    break;
                case MchConstant.BIZ_ITEM_ONLINE:
                    totalProfit += profilt;
                    rechargeProfit += profilt;
                    break;
            }
        }
        agentProfitObj.put("agentpayProfit", agentpayProfit);
        agentProfitObj.put("payProfit", payProfit);
        agentProfitObj.put("rechargeProfit", rechargeProfit);
        agentProfitObj.put("totalProfit", totalProfit);
        JSONObject object = new JSONObject();
        object.put("agentObj", doMapEmpty(agentObj));
        object.put("agentProfitObj", doMapEmpty(agentProfitObj));
        return ResponseEntity.ok(XxPayResponse.buildSuccess(object));
    }

    /**
     * 统计商户数据
     * @return
     */
    @RequestMapping("/statistics/count4mch")
    @ResponseBody
    public ResponseEntity<?> count4Mch(HttpServletRequest request) {
        // 商户数据
        Map mchObj = commonService.mchInfoService.count4Mch();
        JSONObject object = new JSONObject();
        object.put("mchObj", doMapEmpty(mchObj));
        return ResponseEntity.ok(XxPayResponse.buildSuccess(object));
    }

    /**
     * 统计平台数据
     * @return
     */
    @RequestMapping("/statistics/count4plat")
    @ResponseBody
    public ResponseEntity<?> count4Plat(HttpServletRequest request) {
        // 收款数据
        Map payDataObj = commonService.mchAccountHistoryService.count4Data(MchConstant.BIZ_TYPE_TRANSACT);
        // 充值数据
        Map rechargeDataObj = commonService.mchAccountHistoryService.count4Data(MchConstant.BIZ_TYPE_RECHARGE);
        // 代付数据
        Map agentpayDataObj = commonService.mchAccountHistoryService.count4Data(MchConstant.BIZ_TYPE_AGENTPAY);

        Long payPlatProfit = Long.parseLong(payDataObj.get("totalPlatProfit").toString());
        Long agentpayPlatProfit = Long.parseLong(agentpayDataObj.get("totalPlatProfit").toString());
        Long rechargePlatProfit = Long.parseLong(rechargeDataObj.get("totalPlatProfit").toString());
        Long totalPlatProfit = payPlatProfit + agentpayPlatProfit + rechargePlatProfit;

        Long payPlatAmount = Long.parseLong(payDataObj.get("totalAmount").toString());
        Long agentpayPlatAmount = Long.parseLong(agentpayDataObj.get("totalAmount").toString());
        Long rechargePlatAmount = Long.parseLong(rechargeDataObj.get("totalAmount").toString());
        Long totalPlatAmount = payPlatAmount + agentpayPlatAmount + rechargePlatAmount;

        JSONObject object = new JSONObject();
        object.put("payDataObj", doMapEmpty(payDataObj));
        object.put("rechargeDataObj", doMapEmpty(rechargeDataObj));
        object.put("agentpayDataObj", doMapEmpty(agentpayDataObj));
        object.put("totalPlatProfit", totalPlatProfit);
        object.put("totalPlatAmount", totalPlatAmount);
        return ResponseEntity.ok(XxPayResponse.buildSuccess(object));
    }

    /**
     * 统计代付数据
     * @return
     */
    @RequestMapping("/statistics/count4agentpay")
    @ResponseBody
    public ResponseEntity<?> count4Agentpay(HttpServletRequest request) {
        // 商户代付数据
        Map agentpayDataObj = commonService.mchAccountHistoryService.count4Data(MchConstant.BIZ_TYPE_AGENTPAY);
        // 商户充值数据
        JSONObject object = new JSONObject();
        Map rechargeDataObj = commonService.mchAccountHistoryService.count4Data(MchConstant.BIZ_TYPE_RECHARGE);
        object.put("agentpayDataObj", doMapEmpty(agentpayDataObj));
        object.put("rechargeDataObj", doMapEmpty(rechargeDataObj));
        return ResponseEntity.ok(XxPayResponse.buildSuccess(object));
    }

    /**
     * 平台首页统计优化
     * @param request
     * @return
     */
    @RequestMapping("/statistics/platCount")
    @ResponseBody
    public ResponseEntity<?> platCount(HttpServletRequest request) {
        // 今日
        String todayStr = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        Date today = DateUtil.str2date(todayStr, "yyyy-MM-dd");
        // 昨日
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -1);
        String yesterdayStr = new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
        Date yesterday = DateUtil.str2date(yesterdayStr, "yyyy-MM-dd");

        // 获取今日平台数据
        StatisticsPlat todayCount = commonService.statisticsPlatService.findByPrimaryKey(today);
        // 获取昨日平台数据
        StatisticsPlat yesterdayCount = commonService.statisticsPlatService.findByPrimaryKey(yesterday);
        // 获取汇总数据
        Map collectCount = commonService.statisticsPlatService.countAll();

        JSONObject object = new JSONObject();
        object.put("todayCount", todayCount);
        object.put("yesterdayCount", yesterdayCount);
        object.put("collectCount", collectCount);
        return ResponseEntity.ok(XxPayResponse.buildSuccess(object));
    }

    /**
     * 商户充值排行
     * @return
     */
    @RequestMapping("/data/count4MchTop")
    @ResponseBody
    public ResponseEntity<?> count4mchTop(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        Date createTimeStart = DateUtil.str2date(getString(param, "createTimeStart"), DateUtil.FORMAT_YYYY_MM_DD);
        Date createTimeEnd = DateUtil.str2date(getString(param, "createTimeEnd"), DateUtil.FORMAT_YYYY_MM_DD);
        Long agentId = getLong(param, "agentId");
        Long mchId = getLong(param, "mchId");
        // 商户充值排行
        Long count = commonService.statisticsMchService.count2MchTop(agentId, mchId, createTimeStart, createTimeEnd);
        List<Map> mchTopList = commonService.statisticsMchService.mchTopList((getPageIndex(param) - 1) * getPageSize(param), getPageSize(param), agentId, mchId, createTimeStart, createTimeEnd);
        return ResponseEntity.ok(XxPayPageRes.buildSuccess(mchTopList, Math.toIntExact(count)));
    }

    /**
     * 代理商分润排行
     * @return
     */
    @RequestMapping("/data/count4AgentTop")
    @ResponseBody
    public ResponseEntity<?> count4AgentTop(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        Long agentId = getLong(param, "agentId");
        String bizType = getString(param, "bizType");
        String createTimeStart = getString(param, "createTimeStart");
        String createTimeEnd = getString(param, "createTimeEnd");
        // 代理商分润排行
        List<Map> agentTopList = commonService.mchAccountHistoryService.count4AgentTop(agentId, bizType,createTimeStart, createTimeEnd);
        List<Map> agentTopList2 = new LinkedList<>();
        for(Map map : agentTopList) {
            agentTopList2.add(doMapEmpty(map));
        }
        return ResponseEntity.ok(XxPayResponse.buildSuccess(agentTopList2));
    }

    /**
     * 支付产品统计
     * @return
     */
    @RequestMapping("/data/count4PayProduct")
    @ResponseBody
    public ResponseEntity<?> count4PayProduct(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        String createTimeStart = getString(param, "createTimeStart");
        String createTimeEnd = getString(param, "createTimeEnd");
        // 支付产品统计
        List<Map> payProductList = commonService.payOrderService.count4PayProduct(createTimeStart, createTimeEnd);
        List<Map> payProductList2 = payProductList.stream().map(this::doMapEmpty).collect(Collectors.toCollection(LinkedList::new));
        return ResponseEntity.ok(XxPayResponse.buildSuccess(payProductList2));
    }

    /**
     * 支付通道统计
     * @return
     */
    @RequestMapping("/data/count4PayPassage")
    @ResponseBody
    public ResponseEntity<?> count4PayPassage(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        Date createTimeStart = DateUtil.str2date(getString(param, "createTimeStart"), DateUtil.FORMAT_YYYY_MM_DD);
        Date createTimeEnd = DateUtil.str2date(getString(param, "createTimeEnd"), DateUtil.FORMAT_YYYY_MM_DD);
        int count = Math.toIntExact(commonService.statisticsPayPassageService.count4PayPassage(createTimeStart, createTimeEnd));
        List<Map> mapList = commonService.statisticsPayPassageService.countList4PayPassage((getPageIndex(param) - 1) * getPageSize(param), getPageSize(param), createTimeStart, createTimeEnd);

        return ResponseEntity.ok(XxPayPageRes.buildSuccess(mapList, count));
    }

    /**
     * 支付通道子账户统计
     * @return
     */
    @RequestMapping("/data/count4PayPassageAccount")
    @ResponseBody
    public ResponseEntity<?> count4PayPassageAccount(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        Integer payPassageId = param.getInteger("payPassageId");
        Date createTimeStart = DateUtil.str2date(getString(param, "createTimeStart"), DateUtil.FORMAT_YYYY_MM_DD);
        Date createTimeEnd = DateUtil.str2date(getString(param, "createTimeEnd"), DateUtil.FORMAT_YYYY_MM_DD);
        int count = Math.toIntExact(commonService.statisticsPayPassageService.count4PayPassageAccount(payPassageId, createTimeStart, createTimeEnd));
        List<Map> mapList = commonService.statisticsPayPassageService.countList4PayPassageAccount((getPageIndex(param) - 1) * getPageSize(param), getPageSize(param), createTimeStart, createTimeEnd, payPassageId);

        return ResponseEntity.ok(XxPayPageRes.buildSuccess(mapList, count));
    }

    @RequestMapping("/data/selectMchInfo")
    @ResponseBody
    public XxPayResponse selectMchInfo(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        Long mchId = getLong(param, "mchId");
        if (mchId != null) {
            MchInfo mchInfo = commonService.mchInfoService.findByMchId(mchId);
            if (mchInfo == null) { return XxPayResponse.build(RetEnum.RET_SERVICE_MCH_NOT_EXIST); }
        }
        return XxPayResponse.buildSuccess();
    }

    /**
     * 按天成功率统计
     * @return
     */
    @RequestMapping("/data/selectSuccessRate")
    @ResponseBody
    public ResponseEntity<?> selectSuccessRate(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        Long mchId = getLong(param, "mchId");
        Date createTimeStart = DateUtil.str2date(getString(param, "createTimeStart"), DateUtil.FORMAT_YYYY_MM_DD);
        Date createTimeEnd = DateUtil.str2date(getString(param, "createTimeEnd"), DateUtil.FORMAT_YYYY_MM_DD);
        int count = Math.toIntExact(commonService.statisticsMchService.count(createTimeStart, createTimeEnd, mchId));
        List<Map> mchList = commonService.statisticsMchService.list((getPageIndex(param) - 1) * getPageSize(param), getPageSize(param), createTimeStart, createTimeEnd, mchId);

        return ResponseEntity.ok(XxPayPageRes.buildSuccess(mchList,count));
    }

    /**
     * 按小时成功率统计
     * @return
     */
    @RequestMapping("/data/hourSuccessRate")
    @ResponseBody
    public ResponseEntity<?> hourSuccessRate(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        String createTimeStart = getString(param, "createTimeStart");
        String createTimeEnd = getString(param, "createTimeEnd");
        Long mchId = getLong(param, "mchId");
        if(!timeDiff(createTimeStart,createTimeEnd)) {
            System.out.println(!timeDiff(createTimeStart,createTimeEnd));
            return ResponseEntity.ok(BizResponse.build(RetEnum.RET_MGR_TIME_DIFF));
        }
        List<Map> successRateList = commonService.payOrderService.hourSuccessRate((getPageIndex(param) -1) * getPageSize(param), getPageSize(param),createTimeStart,createTimeEnd,mchId);
        Map<String,Object> countMap = commonService.payOrderService.countHourSuccessRate(createTimeStart,createTimeEnd,mchId);
        int count = (int)(long)countMap.get("totalCount");
        List<Map> successRateList2 = new LinkedList<>();
        for(Map map : successRateList) {
            String successRate = ((BigDecimal) map.get("successRate")).multiply(new BigDecimal(100)).setScale(2,BigDecimal.ROUND_HALF_UP).toString() + "%";
            String dateType = map.get("dateType") + " 时";
            map.put("dateType",dateType);
            map.put("successRate",successRate);
            successRateList2.add(doMapEmpty(map));
        }
        return ResponseEntity.ok(XxPayPageRes.buildSuccess(successRateList2,count));
    }

    /**
     * 订单近七日成功率
     * @return
     */
    @RequestMapping("/data/dateRate")
    @ResponseBody
    public ResponseEntity<?> dateRate(HttpServletRequest request) {
        Map object = new LinkedHashMap();
        Map dateRate = new LinkedHashMap();
        for(int i = 0 ; i < 7 ; i++){
            String day = new SimpleDateFormat("yyyy-MM-dd").format(new Date().getTime()-24*60*60*1000*i);
            String dayStart = day + " 00:00:00";
            String dayEnd = day + " 23:59:59";
            // 订单近七日成功率查询
            dateRate = commonService.payOrderService.dateRate(dayStart, dayEnd);
            if (dateRate != null) {
                BigDecimal successRate = ((BigDecimal) dateRate.get("successRate")).multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP);
                dateRate.put("successRate",successRate);
            }
            object.put(i,day);
            int y = i + 7;
            object.put(y, doMapEmpty(dateRate));
        }
        return ResponseEntity.ok(XxPayResponse.buildSuccess(object));
    }

    /**
     * 订单近十二小时成功率
     * @return
     */
    @RequestMapping("/data/hourRate")
    @ResponseBody
    public ResponseEntity<?> hourRate(HttpServletRequest request) {
        Map object = new LinkedHashMap();
        Map hourRate = new LinkedHashMap();
        for(int i = 0 ; i < 12 ; i++){
            String day = new SimpleDateFormat("yyyy-MM-dd HH").format(new Date().getTime()-60*60*1000*i);
            String dayStart = day + ":00:00";
            String dayEnd = day + ":59:59";
            // 订单近十二小时成功率查询
            hourRate = commonService.payOrderService.hourRate(dayStart, dayEnd);
            if (hourRate != null) {
                BigDecimal successRate = ((BigDecimal) hourRate.get("successRate")).multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP);
                hourRate.put("successRate",successRate);
            }
            String day2 = new SimpleDateFormat("HH时").format(new Date().getTime()-60*60*1000*i);
            object.put(i,day2);
            int y = i + 12;
            object.put(y, doMapEmpty(hourRate));
        }
        return ResponseEntity.ok(XxPayResponse.buildSuccess(object));
    }

    /**
     * 近七日平台交易金额
     * @return
     */
    @RequestMapping("/statistics/orderDayAmount")
    @ResponseBody
    public ResponseEntity<?> orderDayAmount(HttpServletRequest request) {
        Map object = new LinkedHashMap();
        Map dayAmount = new LinkedHashMap();
        for(int i = 0 ; i < 7 ; i++){
            String day = new SimpleDateFormat("yyyy-MM-dd").format(new Date().getTime()-24*60*60*1000*i);
            String dayStart = day + " 00:00:00";
            String dayEnd = day + " 23:59:59";
            // 每日交易金额查询
            dayAmount = commonService.payOrderService.orderDayAmount(null,dayStart, dayEnd);
            object.put(i,day);
            int y = i + 7;
            object.put(y, doMapEmpty(dayAmount));
        }
        return ResponseEntity.ok(XxPayResponse.buildSuccess(object));
    }

    /**
     * 代理商分润日统计
     * @return
     */
    @RequestMapping("/data/agentDailyProfit")
    @ResponseBody
    public ResponseEntity<?> agentDailyProfit(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        Long agentId = getLong(param, "agentId");
        Byte bizType = getByte(param, "bizType");
        String createTimeStart = getString(param, "createTimeStart");
        String createTimeEnd = getString(param, "createTimeEnd");
        int count = commonService.mchAccountHistoryService.count4DailyProfit(null, agentId, bizType, createTimeStart, createTimeEnd);
        if (count <= 0) return ResponseEntity.ok(XxPayPageRes.buildSuccess());
        List<Map> map = commonService.mchAccountHistoryService.dailyProfit((getPageIndex(param)-1) * getPageSize(param), getPageSize(param), null, agentId, bizType, createTimeStart, createTimeEnd);
        return ResponseEntity.ok(XxPayPageRes.buildSuccess(map, count));
    }

    /**
     * 商户分润日统计
     * @return
     */
    @RequestMapping("/data/mchDailyProfit")
    @ResponseBody
    public ResponseEntity<?> mchDailyProfit(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        Long mchId = getLong(param, "mchId");
        Date createTimeStart = DateUtil.str2date(getString(param, "createTimeStart"), DateUtil.FORMAT_YYYY_MM_DD);
        Date createTimeEnd = DateUtil.str2date(getString(param, "createTimeEnd"), DateUtil.FORMAT_YYYY_MM_DD);
        int count = Math.toIntExact(commonService.statisticsMchService.count(createTimeStart, createTimeEnd, mchId));
        List<Map> mchList = commonService.statisticsMchService.list((getPageIndex(param) - 1) * getPageSize(param), getPageSize(param), createTimeStart, createTimeEnd, mchId);

        return ResponseEntity.ok(XxPayPageRes.buildSuccess(mchList, count));
    }

    /**
     * 平台分润日统计
     * @return
     */
    @RequestMapping("/data/platDailyProfit")
    @ResponseBody
    public ResponseEntity<?> platDailyProfit(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        Date createTimeStart = DateUtil.str2date(getString(param, "createTimeStart"), DateUtil.FORMAT_YYYY_MM_DD);
        Date createTimeEnd = DateUtil.str2date(getString(param, "createTimeEnd"), DateUtil.FORMAT_YYYY_MM_DD);
        int count = Math.toIntExact(commonService.statisticsPlatService.count2(null, createTimeStart, createTimeEnd));
        List<StatisticsPlat> platList = commonService.statisticsPlatService.select2((getPageIndex(param) - 1) * getPageSize(param), getPageSize(param), null, createTimeStart, createTimeEnd);
        return ResponseEntity.ok(XxPayPageRes.buildSuccess(platList, count));
    }

    private Map doMapEmpty(Map map) {
        if(map == null) return map;
        if(null == map.get("totalCount")) map.put("totalCount", 0);
        if(null == map.get("totalAmount")) map.put("totalAmount", 0);
        if(null == map.get("totalMchIncome")) map.put("totalMchIncome", 0);
        if(null == map.get("totalAgentProfit")) map.put("totalAgentProfit", 0);
        if(null == map.get("totalPlatProfit")) map.put("totalPlatProfit", 0);
        if(null == map.get("totalChannelCost")) map.put("totalChannelCost", 0);
        if(null == map.get("totalBalance")) map.put("totalBalance", 0);
        if(null == map.get("totalSettAmount")) map.put("totalSettAmount", 0);
        if(null == map.get("payProfit")) map.put("payProfit", 0);
        if(null == map.get("agentpayProfit")) map.put("agentpayProfit", 0);
        if(null == map.get("successRate")) map.put("successRate", 0);
        return map;
    }

    private boolean timeDiff(String createTimeStart,String createTimeEnd){
        Calendar calendar1 = Calendar.getInstance();
        calendar1.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(createTimeStart,new ParsePosition(0)));

        Calendar calendar2 = Calendar.getInstance();
        calendar2.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(createTimeEnd,new ParsePosition(0)));
        Long timeDiff = calendar2.getTimeInMillis() - calendar1.getTimeInMillis();
        if (timeDiff > 24*60*60*1000){
            return false;
        }
        return true;
    }

    /**
     * 修正平台日统计
     * @return
     */
    @RequestMapping("/data/plat/correct")
    @ResponseBody
    public ResponseEntity<?> platCorrect(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        String statisticsDateParam = getStringRequired(param, "statisticsDate");

        ArrayList<String> timeStrList = null;
        Object object = DateUtil.getTimeStrList(statisticsDateParam);
        if (object instanceof String) {
            return ResponseEntity.ok(BizResponse.build(RetEnum.RET_COMM_PARAM_ERROR, (String) object));
        }
        if (object instanceof ArrayList) {
            timeStrList = (ArrayList<String>) object;
        }
        if (CollectionUtils.isEmpty(timeStrList)) return ResponseEntity.ok(XxPayResponse.build(RetEnum.RET_COMM_PARAM_ERROR));

        for (String statisticsDate : timeStrList) {
            String statisticsDateStart = statisticsDate + " 00:00:00";
            String statisticsDateEnd = statisticsDate + " 23:59:59";

            // 全部支付订单统计
            JSONObject allPayData = commonService.statisticsPlatService.payCorrect(null, null, null, null, statisticsDateStart, statisticsDateEnd);
            // 成功支付订单统计
            JSONObject successPayData = commonService.statisticsPlatService.payCorrect(null, null, null, Arrays.asList(PayConstant.PAY_STATUS_SUCCESS, PayConstant.PAY_STATUS_COMPLETE), statisticsDateStart, statisticsDateEnd);

            // 全部代付订单统计
            JSONObject allAgentpayData = commonService.statisticsPlatService.agentpayCorrect(null, null, statisticsDateStart, statisticsDateEnd);
            // 成功代付订单统计
            JSONObject successAgentpayData = commonService.statisticsPlatService.agentpayCorrect(null, PayConstant.AGENTPAY_STATUS_SUCCESS, statisticsDateStart, statisticsDateEnd);

            // 成功充值数据统计
            JSONObject successRechargeData = commonService.statisticsPlatService.rechargeCorrectSuccess(null, statisticsDateStart, statisticsDateEnd);


            //更新平台统计表
            StatisticsPlat updateRecord = new StatisticsPlat();
            updateRecord.setStatisticsDate(DateUtil.str2date(statisticsDate, DateUtil.FORMAT_YYYY_MM_DD));
            //支付
            updateRecord.setPayTotalAmount(allPayData.getLong("totalAmount"));
            updateRecord.setPayTotalCount(allPayData.getInteger("totalCount"));
            updateRecord.setPaySuccessAmount(successPayData.getLong("totalAmount"));
            updateRecord.setPaySuccessCount(successPayData.getInteger("totalCount"));
            updateRecord.setPayTotalProfit(successPayData.getLong("totalPlatProfit"));
            //代付
            updateRecord.setAgentPayTotalAmount(allAgentpayData.getLong("totalAmount"));
            updateRecord.setAgentPayTotalCount(allAgentpayData.getInteger("totalCount"));
            updateRecord.setAgentPaySuccessAmount(successAgentpayData.getLong("totalAmount"));
            updateRecord.setAgentPaySuccessCount(successAgentpayData.getInteger("totalCount"));
            Long profit = 0L;//平台代付分润
            if (StringUtils.isNotBlank(successAgentpayData.getString("agentpayOrderIdList"))) {
                List<String> agentpayOrderIdList = Arrays.asList(successAgentpayData.getString("agentpayOrderIdList").split(","));
                List<MchAccountHistory> historyList = commonService.mchAccountHistoryService.selectList(agentpayOrderIdList);
                for (MchAccountHistory history : historyList) {
                    profit += history.getPlatProfit();
                }
            }
            updateRecord.setAgentPayTotalProfit(profit);
            //充值
            updateRecord.setRechargeSuccessAmount(successRechargeData.getLong("totalAmount"));
            updateRecord.setRechargeSuccessCount(successRechargeData.getInteger("totalCount"));
            updateRecord.setRechargeTotalProfit(successRechargeData.getLong("totalPlatProfit"));

            int count = commonService.statisticsPlatService.updateByPrimaryKey(updateRecord);
            if (count == 0) {
                commonService.statisticsPlatService.add(updateRecord);
            }
        }
        return ResponseEntity.ok(XxPayResponse.buildSuccess());
    }

    /**
     * 修正商户日统计
     * @return
     */
    @RequestMapping("/data/mch/correct")
    @ResponseBody
    public ResponseEntity<?> mchCorrect(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        Long mchId = getLong(param, "mchId");
        String statisticsDateParam = getStringRequired(param, "statisticsDate");

        ArrayList<String> timeStrList = null;
        Object object = DateUtil.getTimeStrList(statisticsDateParam);
        if (object instanceof String) {
            return ResponseEntity.ok(BizResponse.build(RetEnum.RET_COMM_PARAM_ERROR, (String) object));
        }
        if (object instanceof ArrayList) {
            timeStrList = (ArrayList<String>) object;
        }
        if (CollectionUtils.isEmpty(timeStrList)) return ResponseEntity.ok(XxPayResponse.build(RetEnum.RET_COMM_PARAM_ERROR));

        MchInfo searchMchInfo = null;
        if (mchId != null) {
            searchMchInfo = commonService.mchInfoService.findByMchId(mchId);
        }
        List<MchInfo> mchInfoList = commonService.mchInfoService.select(0, Integer.MAX_VALUE, searchMchInfo);

        for (MchInfo mchInfo : mchInfoList) {
            for (String statisticsDate : timeStrList) {
                String statisticsDateStart = statisticsDate + " 00:00:00";
                String statisticsDateEnd = statisticsDate + " 23:59:59";

                // 全部支付订单统计
                JSONObject allPayData = commonService.statisticsPlatService.payCorrect(mchInfo.getMchId(), null, null, null, statisticsDateStart, statisticsDateEnd);
                // 成功支付订单统计
                JSONObject successPayData = commonService.statisticsPlatService.payCorrect(mchInfo.getMchId(), null, null, Arrays.asList(PayConstant.PAY_STATUS_SUCCESS, PayConstant.PAY_STATUS_COMPLETE), statisticsDateStart, statisticsDateEnd);

                // 全部代付订单统计
                JSONObject allAgentpayData = commonService.statisticsPlatService.agentpayCorrect(mchInfo.getMchId(), null, statisticsDateStart, statisticsDateEnd);
                // 成功代付订单统计
                JSONObject successAgentpayData = commonService.statisticsPlatService.agentpayCorrect(mchInfo.getMchId(), PayConstant.AGENTPAY_STATUS_SUCCESS, statisticsDateStart, statisticsDateEnd);

                // 成功充值数据统计
                JSONObject successRechargeData = commonService.statisticsPlatService.rechargeCorrectSuccess(mchInfo.getMchId(), statisticsDateStart, statisticsDateEnd);

                //更新平台统计表
                StatisticsMch updateRecord = new StatisticsMch();
                updateRecord.setMchId(mchInfo.getMchId());
                updateRecord.setStatisticsDate(DateUtil.str2date(statisticsDate, DateUtil.FORMAT_YYYY_MM_DD));
                //支付
                updateRecord.setPayTotalAmount(allPayData.getLong("totalAmount"));
                updateRecord.setPayTotalCount(allPayData.getInteger("totalCount"));
                updateRecord.setPaySuccessAmount(successPayData.getLong("totalAmount"));
                updateRecord.setPaySuccessCount(successPayData.getInteger("totalCount"));
                updateRecord.setPayTotalFee(successPayData.getLong("totalAmount") - successPayData.getLong("totalMchIncome"));
                //代付
                updateRecord.setAgentPayTotalAmount(allAgentpayData.getLong("totalAmount"));
                updateRecord.setAgentPayTotalCount(allAgentpayData.getInteger("totalCount"));
                updateRecord.setAgentPaySuccessAmount(successAgentpayData.getLong("totalAmount"));
                updateRecord.setAgentPaySuccessCount(successAgentpayData.getInteger("totalCount"));
                updateRecord.setAgentPayTotalFee(successAgentpayData.getLong("totalFee"));
                updateRecord.setRechargeSuccessAmount(successRechargeData.getLong("totalAmount"));
                updateRecord.setRechargeSuccessCount(successRechargeData.getInteger("totalCount"));
                updateRecord.setRechargeTotalFee(successRechargeData.getLong("totalFee"));

                int count = commonService.statisticsMchService.updateByPrimaryKey(updateRecord);
                if (count == 0) {
                    commonService.statisticsMchService.add(updateRecord);
                }
            }
        }
        return ResponseEntity.ok(XxPayResponse.buildSuccess());
    }

    /**
     * 修正通道日统计
     * @return
     */
    @RequestMapping("/data/passage/correct")
    @ResponseBody
    public ResponseEntity<?> passageCorrect(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        Integer payPassageId = getInteger(param, "payPassageId");
        String statisticsDateParam = getStringRequired(param, "statisticsDate");

        ArrayList<String> timeStrList = null;
        Object object = DateUtil.getTimeStrList(statisticsDateParam);
        if (object instanceof String) {
            return ResponseEntity.ok(BizResponse.build(RetEnum.RET_COMM_PARAM_ERROR, (String) object));
        }
        if (object instanceof ArrayList) {
            timeStrList = (ArrayList<String>) object;
        }
        if (CollectionUtils.isEmpty(timeStrList)) return ResponseEntity.ok(XxPayResponse.build(RetEnum.RET_COMM_PARAM_ERROR));

        PayPassageAccount account = null;
        if (payPassageId != null) {
            account = new PayPassageAccount();
            account.setPayPassageId(payPassageId);
        }
        List<PayPassageAccount> payPassageAccountList = commonService.payPassageAccountService.select(0, Integer.MAX_VALUE, account);

        for (PayPassageAccount payPassageAccount : payPassageAccountList) {
            for (String statisticsDate : timeStrList) {
                String statisticsDateStart = statisticsDate + " 00:00:00";
                String statisticsDateEnd = statisticsDate + " 23:59:59";

                // 全部支付订单统计
                JSONObject allPayData = commonService.statisticsPlatService.payCorrect(null, payPassageAccount.getId(), payPassageAccount.getPayPassageId(), null, statisticsDateStart, statisticsDateEnd);
                // 成功支付订单统计
                JSONObject successPayData = commonService.statisticsPlatService.payCorrect(null, payPassageAccount.getId(), payPassageAccount.getPayPassageId(), Arrays.asList(PayConstant.PAY_STATUS_SUCCESS, PayConstant.PAY_STATUS_COMPLETE), statisticsDateStart, statisticsDateEnd);

                //更新平台统计表
                StatisticsPayPassage updateRecord = new StatisticsPayPassage();
                updateRecord.setPayPassageId(payPassageAccount.getPayPassageId());
                updateRecord.setPayPassageAccountId(payPassageAccount.getId());
                updateRecord.setStatisticsDate(DateUtil.str2date(statisticsDate, DateUtil.FORMAT_YYYY_MM_DD));
                //支付
                updateRecord.setPayTotalAmount(allPayData.getLong("totalAmount"));
                updateRecord.setPayTotalCount(allPayData.getInteger("totalCount"));
                updateRecord.setPaySuccessAmount(successPayData.getLong("totalAmount"));
                updateRecord.setPaySuccessCount(successPayData.getInteger("totalCount"));
                updateRecord.setTotalChannelCost(successPayData.getLong("totalChannelCost"));

                int count = commonService.statisticsPayPassageService.updateByPrimaryKey(updateRecord);
                if (count == 0) {
                    commonService.statisticsPayPassageService.add(updateRecord);
                }
            }
        }
        return ResponseEntity.ok(XxPayResponse.buildSuccess());
    }

}
